class ApiService {
  constructor() {
    this.baseUrl = 'http://localhost:3000/api';
    this.storageKey = 'characters';
    this.zhipuBaseUrl = 'https://open.bigmodel.cn/api/paas/v4';
    this.apiKey = '9e2458a8acf46274d1c1b9418eec500c.oBojpibVHt3IyXnz'; // 从环境变量或配置中获取
    this.model = 'glm-4-flash'; // 默认模型
    this.agent = "你是一个辩论小能手，你的名字是：{name}，你的性格特征为：{personality}，你的语言风格特征为：{style}。你会根据用户的问题做出符合你性格特征和语言风格特征的答复。每次答复限制在200字以内，可以更少不能更多。"; // 默认agent
  }

  // 角色消息数据存储
  async saveCharacterMessage(message, character, role) {

    try {
      // 校验chararcter,只能是character1或character2
      if (character != 'character1' && character != 'character2') {
        throw new Error('character参数错误');
      }
      let allmessage = await this.getCharacterMessages(character);
      if (!Array.isArray(allmessage)) {
        allmessage = [];
      }
      allmessage.push({ "role": role, "content": message });
      localStorage.setItem(`${this.storageKey}-${character}-messages`, JSON.stringify(allmessage));

      return true;
    } catch (error) {
      console.error('保存角色消息数据失败:', error);
      return false;
    }
  }
  // 角色消息数据获取
  async getCharacterMessages(character) {
    try {
      // 校验chararcter,只能是character1或character2
      if (character != 'character1' && character != 'character2') {
        throw new Error('character参数错误');
      }

      let data = localStorage.getItem(`${this.storageKey}-${character}-messages`);
      if (!data) {
        const settings = await this.getCharacterSettings(character);
        const personality = settings.personality;
        const style = settings.style;
        const name = settings.name;
        const agent = this.agent.replace('{name}', name).replace('{personality}', personality).replace('{style}', style);
        const messages = [
          { "role": "system", "content": agent },
          { "role": "user", "content": "如果你准备好了，请回答：好的，我准备好了。" },
          { "role": "assistant", "content": "好的，我准备好了。" }
        ]
        localStorage.setItem(`${this.storageKey}-${character}-messages`, JSON.stringify(messages));
        return messages;
      }
      try {
        return JSON.parse(data);
      } catch (error) {
        console.error('解析消息数据失败，重置为初始值:', error);
        localStorage.removeItem(`${this.storageKey}-${character}-messages`);
        return this.getCharacterMessages(character);
      }
    } catch (error) {
      console.error('获取角色消息数据失败:', error);
      return [];
    }
  }



  async getChatResponse(message, character) {
  // 用于获取聊天响应，message为用户消息，character为角色名称，返回值为AI消息
  // 会存储用户消息和AI消息，并返回AI消息
  try {
    // 校验chararcter,只能是character1或character2
    if (character != 'character1' && character != 'character2') {
      throw new Error('character参数错误');
    }
    // 保存用户消息
    if(!await this.saveCharacterMessage(message, character, 'user')){
      throw new Error('保存用户消息失败');
    };
    const messages = await this.getCharacterMessages(character);

    const response = await fetch(`${this.zhipuBaseUrl}/chat/completions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.apiKey}`
      },
      body: JSON.stringify({
        model: this.model,
        messages: messages,
      })
    })

    if (response.ok) {
      const data = await response.json();
      const responsemessage = data.choices[0].message.content;
      // 保存AI消息
      this.saveCharacterMessage(responsemessage, character, 'assistant');
      return responsemessage;
    } else {
      console.error('获取聊天响应失败:', response.status, response.statusText);
      return null;
    }


  }
  catch (error) {
    console.error('获取聊天响应失败:', error);
    return null;
  }
}



  // 获取角色设置
  async getCharacterSettings(character) {
  try {
    // 从localStorage读取
    const data = localStorage.getItem(`${this.storageKey}-${character}`);
    return data ? JSON.parse(data) : this.getDefaultSettings();
  } catch (error) {
    console.error('获取角色设置失败:', error);
    return this.getDefaultSettings();
  }
}

  // 保存角色设置
  async saveCharacterSettings(character, settings) {

  try {
    // 优化存储数据
    let avatarDataUrl = '';
    if (settings.avatar) {
      // 判断是否为base64格式，是则压缩存储

      if (settings.avatar.startsWith('data:image/jpeg;base64,')) {
        // 压缩存储
        avatarDataUrl = await this.compressAvatar(settings.avatar);
      } else {
        // 不压缩存储
        avatarDataUrl = settings.avatar;
      }


    }

    const dataToSave = {
      ...settings,
      avatar: avatarDataUrl
    };

    // 检查数据大小
    const dataSize = new Blob([JSON.stringify(dataToSave)]).size;
    if (dataSize > 1024 * 1024) { // 超过1MB
      throw new Error('数据过大，请减少头像文件大小');
    }

    // 保存到localStorage
    localStorage.setItem(
      `${this.storageKey}-${character}`,
      JSON.stringify(dataToSave)
    );
    return true;
  } catch (error) {
    console.error('保存角色设置失败:', error);
    return false;
  }
}

// 压缩头像数据
compressAvatar(dataUrl) {
  return new Promise((resolve) => {
    const img = new Image();
    img.src = dataUrl;

    img.onload = () => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');

      // 设置最大尺寸
      const maxSize = 200;
      let width = img.width;
      let height = img.height;

      if (width > height) {
        if (width > maxSize) {
          height *= maxSize / width;
          width = maxSize;
        }
      } else {
        if (height > maxSize) {
          width *= maxSize / height;
          height = maxSize;
        }
      }

      canvas.width = width;
      canvas.height = height;
      ctx.drawImage(img, 0, 0, width, height);

      // 转换为压缩后的Data URL
      resolve(canvas.toDataURL('image/jpeg', 0.7));
    };
  });
}

  // 获取所有本地角色数据
  async getLocalCharacterData() {
  try {
    const data = [];
    // 遍历localStorage中所有以storageKey开头的项
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      if (key.startsWith(this.storageKey) && key != (this.storageKey + '-character1') && key != (this.storageKey + '-character2') && key != (this.storageKey + '-user') && key != (this.storageKey + '-character1-messages') && key != (this.storageKey + '-character2-messages')) {
        const item = localStorage.getItem(key);
        if (item) {
          data.push(JSON.parse(item));
        }
      }
    }
    return data;
  } catch (error) {
    console.error('获取本地角色数据失败:', error);
    return [];
  }
}

  async getUserSettings() {
  try {
    const data = localStorage.getItem(`${this.storageKey}-user`);
    return data ? JSON.parse(data) : { name: '', avatar: '' };
  } catch (error) {
    console.error('获取用户设置失败:', error);
    return { name: '', avatar: '' };
  }
}

  async saveUserSettings(settings) {
  try {
    localStorage.setItem(`${this.storageKey}-user`, JSON.stringify(settings));
    return true;
  } catch (error) {
    console.error('保存用户设置失败:', error);
    return false;
  }
}

  // 根据发送者获取头像
  async getAvatarForSender(sender) {
    try {
      if (sender === 'user') {
        const userSettings = await this.getUserSettings();
        return userSettings.avatar || 'assets/images/default-avatar.png';
      } else if (sender === 'character1' || sender === 'character2') {
        const characterSettings = await this.getCharacterSettings(sender);
        return characterSettings.avatar || 'assets/images/default-avatar.png';
      }
      return 'assets/images/default-avatar.png';
    } catch (error) {
      console.error('获取头像失败:', error);
      return 'assets/images/default-avatar.png';
    }
  }

// 清除角色会话历史
clearCharacterHistory() {
  try {
    localStorage.removeItem(`${this.storageKey}-character1-messages`);
    localStorage.removeItem(`${this.storageKey}-character2-messages`);
    return true;
  } catch (error) {
    console.error('清除角色会话历史失败:', error);
    return false;
  }
}

// 获取默认设置
getDefaultSettings() {
  return {
    name: '',
    personality: '',
    style: '',
    avatar: '',
    voice: {}
  };
}



  // 上传文件
  async uploadFile(file) {
  return new Promise((resolve) => {
    const reader = new FileReader();
    reader.onload = (e) => resolve(e.target.result);
    reader.readAsDataURL(file);
  });
}
}

export default new ApiService();
